<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class GetUserFromToken
{
    /**
     * 身份验证.
     *
     * Author : LeePeng
     * email: lp@kuhui.com.cn
     * Date: 15/12/29
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $data=new \stdClass();
        try {

            if (! $user = JWTAuth::parseToken()->authenticate()) {

                return response()->json([
                    'status'=>false,
                    'code' => 400005,
                    'message' => '用户未找到',
                    'data'=>$data,
                ], 401);
            }

        } catch (TokenExpiredException $e) {

            return response()->json([
                'status'=>false,
                'code' => 400001,
                'message' => 'token过期',
                'data'=>$data
            ], 401);

        } catch (TokenInvalidException $e) {

            return response()->json([
                'status'=>false,
                'code' => 400003,
                'message' => 'token非法',
                'data'=>$data
            ], 401);

        } catch (JWTException $e) {

            return response()->json([
                'status'=>false,
                'code' => 400002,
                'message' => 'token缺失',
                'data'=>$data
            ],401);

        }
        return $next($request);
    }
}